package com.xxtx.trade.sysUser.service.impl;

import com.github.pagehelper.PageHelper;
import com.xxtx.trade.common.util.IdCreateUtil;
import com.xxtx.trade.common.util.SpringUserContext;
import com.xxtx.trade.common.util.cache.CacheManager;
import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.common.util.springUtil.SpringUtil;
import com.xxtx.trade.jwt.BaseContextHandler;
import com.xxtx.trade.jwt.JWTExtInfo;
import com.xxtx.trade.jwt.JwtTokenExtUtil;
import com.xxtx.trade.sysUser.bean.*;
import com.xxtx.trade.sysUser.dto.TradeSysMenuDto;
import com.xxtx.trade.sysUser.dto.TradeSysUserDto;
import com.xxtx.trade.sysUser.enums.TradeSysUserStateEnum;
import com.xxtx.trade.sysUser.mapper.TradeRoleMenuMapper;
import com.xxtx.trade.sysUser.mapper.TradeSysMenuMapper;
import com.xxtx.trade.sysUser.mapper.TradeSysRoleMapper;
import com.xxtx.trade.sysUser.mapper.TradeSysUserMapper;
import com.xxtx.trade.sysUser.service.TradeSysMenuService;
import com.xxtx.trade.sysUser.vo.TradeSysMenuVo;
import com.xxtx.trade.sysUser.vo.TradeSysUserVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class TradeSysMenuServiceImpl implements TradeSysMenuService {
    private static final Logger LOGGER = LoggerFactory.getLogger(TradeSysMenuServiceImpl.class);
    @Autowired
    private TradeSysMenuMapper tradeSysMenuMapper;
    @Autowired
    private TradeRoleMenuMapper tradeRoleMenuMapper;
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private SpringUserContext userContext;

    @Autowired
    private TradeSysUserMapper tradeSysUserMapper;
    /**
     * 根据用户id 查询所属菜单
     * @param menuDto
     * @return
     */
    @Override
    public Result selectUserMenus(TradeSysMenuDto menuDto) {
        Result<Object> result = new Result<>();
        try {
            TradeSysUser id = tradeSysUserMapper.selectUserByAccountId(menuDto.getId());
            //查询用户对应的菜单
            List<TradeSysMenu> list = tradeSysMenuMapper.selectMenuByUserId(id.getId());
            //查询出所有的父菜单
            List<TradeSysMenu> pidMenus = tradeSysMenuMapper.selectPidMenus();
            ArrayList<TradeSysMenu> body = null;
            ArrayList<TradeSysMenu> father = new ArrayList<>();
            for (TradeSysMenu pidMenu : pidMenus) {
                if (list != null && list.size() > 0) {
                    for (TradeSysMenu sysMenu : list) {
                        if (sysMenu.getPid().equals(pidMenu.getId())) {
                            if (pidMenu.getBodyMenus() == null) {
                                body = new ArrayList<>();
                                body.add(sysMenu);
                                pidMenu.setBodyMenus(body);
                            } else {
                                pidMenu.getBodyMenus().add(sysMenu);
                            }
                        }
                    }
                }
            }
            Iterator<TradeSysMenu> iterator = pidMenus.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().getBodyMenus() == null) {
                    iterator.remove();
                }
            }
            TradeSysUserVo userVo = new TradeSysUserVo();
            userVo.setUserMenus(pidMenus);
            userVo.setId(id.getId());
            userVo.setAccountName(id.getAccountName());
            userVo.setCreateTime(id.getCreateTime());
            userVo.setNickName(id.getNickName());
            userVo.setPhone(id.getPhone());
            userVo.setState(id.getState());
            userVo.setAgentId(id.getAgentId());
            userVo.setStateName(id.getState().equals(TradeSysUserStateEnum.ACCOUNT_STATE_NORMAL.getCode()) ? "启用" : "禁用");
            userVo.setAgentPathId(id.getAgentPathId());
            userVo.setAgentPathName(id.getAgentPathName());
            userVo.setToken("");
            //获取用户对应的角色
            BaseContextHandler.setAgentId(userVo.getAgentId());
            List<TradeSysRole> roles = tradeSysRoleMapper.selectInfoByUserId(id.getId());
            userVo.setRoles(roles);
            result.setData(userVo);
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.info("查询代理商的 菜单信息错误，错误信息为{}",menuDto);
            result.setCode(400);
            result.setMessage("系统繁忙 请稍后再试");
        }
        return result;
    }
    @Autowired
    private TradeSysRoleMapper tradeSysRoleMapper;
    /**
     *  创建菜单
     * @param menuDto
     * @return
     */
    @Override
    public Result createMenus(TradeSysMenuDto menuDto) {
        Result<Object> result = new Result<>();
        try {
            if (StringUtils.isEmpty(menuDto.getPath())||StringUtils.isEmpty(menuDto.getName())){
                result.setCode(400);
                result.setMessage("请确保信息完整！");
                return result;
            }
            TradeSysMenu menu = new TradeSysMenu();
            menu.setIcon(menuDto.getIcon());
            menu.setId(IdCreateUtil.getId());
            menu.setCreateTime(new Date());
            menu.setRemark(menuDto.getRemark());
            menu.setName(menuDto.getName());
            menu.setPath(menuDto.getPath());
            menu.setSort(menuDto.getSort());
            menu.setPid(menuDto.getPid()==null? "0":menuDto.getPid());
            menu.setState(menuDto.getState());
            tradeSysMenuMapper.insertSelective(menu);
        }catch (Exception e){
            LOGGER.info("创建订单错误，错误信息为{}",menuDto);
            result.setCode(400);
            result.setMessage("创建失败");
        }
        return result;
    }

    /**
     * 查询所有菜单（根据角色）
     * @param menuDto
     * @return
     */
    @Override
    public Result selectAllMenus(TradeSysMenuDto menuDto) {
        Result<Object> result = new Result<>();
        try {
            if (menuDto.getRoleId()!=null){
                //查询是否被选用
                List<String> menus = tradeRoleMenuMapper.selectMenuByRoleId(menuDto.getRoleId());
                //查询所有父菜单
                List<TradeSysMenu> list= tradeSysMenuMapper.selectPidMenus();
                List<TradeSysMenu> bodys=null;
                if (list!=null) {
                    for (TradeSysMenu sysMenu : list) {
                        //查询所有子菜单
                        bodys = tradeSysMenuMapper.selectBodyMenus(sysMenu.getId());
                        if (bodys != null) {
                            for (TradeSysMenu body : bodys) {
                                if (menus != null && menus.contains(body.getId())) {
                                    body.setIsCheck(1);
                                } else {
                                    body.setIsCheck(2);
                                }
                            }
                        }
                        sysMenu.setBodyMenus(bodys);
                    }
                }
                result.setData(list);
            }else {
                //查询所有父菜单
                PageHelper.startPage(menuDto.getPageNo(),menuDto.getPerPageNum(),"sort");
                List<TradeSysMenu> list= tradeSysMenuMapper.selectPidMenus();
                List<TradeSysMenu> bodys=null;
                if (list!=null) {
                    for (TradeSysMenu sysMenu : list) {
                        //查询所有子菜单
                        bodys = tradeSysMenuMapper.selectBodyMenus(sysMenu.getId());
                        sysMenu.setBodyMenus(bodys);
                    }
                }
                result.setData(list);
            }
        }catch (Exception e){
            LOGGER.info("查看菜单信息错误，错误信息为{}",menuDto);
            result.setCode(400);
            result.setMessage("查看菜单信息错误");
        }
        return result;
    }

    /**
     * 删除菜单
     * @param menuDto
     * @return
     */
    @Override
    public Result delectMenus(TradeSysMenuDto menuDto) {
        Result<Object> result = new Result<>();
        try {
            tradeSysMenuMapper.deleteByPrimaryKey(menuDto.getId());
        }catch (Exception e){
            LOGGER.info("删除子菜单错误，错误信息为{}",menuDto);
            result.setCode(400);
            result.setMessage("删除失败，请检查入参");
        }
        return result;
    }

    /**
     *
     * @param menuDto
     * @return
     */
    @Override
    public Result updateMenus(TradeSysMenuDto menuDto) {
        Result<Object> result = new Result<>();
        try {
            tradeSysMenuMapper.updateByPrimaryKeySelective(menuDto);
        }catch (Exception e){
            LOGGER.info("更改角色的子菜单错误，错误信息为{}",menuDto);
            result.setCode(400);
            result.setMessage("更改失败，请检查入参");
        }
        return result;
    }
}
